<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>国显科技演讲比赛实时投票</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        accent: '#6366F1',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .animate-float {
                animation: float 3s ease-in-out infinite;
            }
            .shadow-custom {
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            }
        }

        @keyframes float {
            0% {
                transform: translateY(0px);
            }
            50% {
                transform: translateY(-10px);
            }
            100% {
                transform: translateY(0px);
            }
        }

        /* 进度条样式 */
        .progress-bar {
            transition: width 1s ease-in-out;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen">
    <header class="bg-white/80 backdrop-blur-md shadow-md fixed w-full top-0 z-50">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-bar-chart text-primary text-2xl"></i>
                <h1 class="text-2xl font-bold text-dark">国显科技演讲比赛实时投票</h1>
            </div>
            <nav class="hidden md:flex space-x-6">
                <a href="/" class="text-primary font-medium hover:text-primary/80 transition-colors">主界面</a>
                <a href="/admin" class="text-dark font-medium hover:text-primary transition-colors">后台管理</a>
            </nav>
            <div class="md:hidden">
                <button id="menu-toggle" class="text-dark focus:outline-none">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="md:hidden hidden bg-white border-t border-gray-100">
            <div class="container mx-auto px-4 py-2 space-y-2">
                <a href="/" class="block py-2 text-primary font-medium">主界面</a>
                <a href="/admin" class="block py-2 text-dark font-medium">后台管理</a>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 pt-28 pb-16">
        <!-- 轮次选择器 -->
        <div class="mb-8 text-center">
            <div class="inline-flex p-1 bg-gray-100 rounded-lg shadow-inner">
                <button class="round-btn px-6 py-3 rounded-lg bg-primary text-white font-medium" data-round="1">
                    第一轮
                </button>
                <button class="round-btn px-6 py-3 rounded-lg text-dark font-medium" data-round="2">
                    第二轮
                </button>
                <button class="round-btn px-6 py-3 rounded-lg text-dark font-medium" data-round="3">
                    第三轮
                </button>
                <button class="round-btn px-6 py-3 rounded-lg text-dark font-medium" data-round="4">
                    总决赛
                </button>
            </div>
        </div>

        <!-- 数据更新状态 -->
        <div class="flex justify-center mb-6">
            <div id="update-status" class="flex items-center text-sm text-gray-500">
                <span id="last-update" class="mr-2">最后更新: 加载中...</span>
                <div class="relative inline-flex">
                    <div class="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div>
                </div>
            </div>
        </div>

        <!-- 图表容器 -->
        <div class="bg-white rounded-xl shadow-custom p-6 mb-8 transition-all duration-300 hover:shadow-lg">
            <div class="h-[500px]">
                <canvas id="votingChart"></canvas>
            </div>
        </div>

        <!-- 数据卡片区域 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div class="bg-white rounded-xl shadow-custom p-6 transition-all duration-300 hover:shadow-lg">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-dark">最高票数选手</h3>
                    <i class="fa fa-trophy text-amber-500 text-2xl"></i>
                </div>
                <div id="highest-score" class="text-2xl font-bold text-primary">
                    <span class="animate-pulse">加载中...</span>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-custom p-6 transition-all duration-300 hover:shadow-lg">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-dark">本轮平均票数</h3>
                    <i class="fa fa-line-chart text-blue-500 text-2xl"></i>
                </div>
                <div id="average-score" class="text-2xl font-bold text-blue-500">
                    <span class="animate-pulse">加载中...</span>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow-custom p-6 transition-all duration-300 hover:shadow-lg">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-dark">选手数量</h3>
                    <i class="fa fa-users text-green-500 text-2xl"></i>
                </div>
                <div id="contestant-count" class="text-2xl font-bold text-green-500">
                    <span class="animate-pulse">加载中...</span>
                </div>
            </div>
        </div>
    </main>

    <script>
        // 移动端菜单切换
        document.getElementById('menu-toggle').addEventListener('click', function() {
            const mobileMenu = document.getElementById('mobile-menu');
            mobileMenu.classList.toggle('hidden');
        });

        // 初始化图表
        let votingChart;
        let currentRound = '1';
        let lastUpdateTime = new Date();

        function initChart(labels, data) {
            const ctx = document.getElementById('votingChart').getContext('2d');
            
            // 如果图表已存在，销毁它
            if (votingChart) {
                votingChart.destroy();
            }
            
            // 计算颜色渐变
            const gradient = ctx.createLinearGradient(0, 0, 0, 400);
            gradient.addColorStop(0, 'rgba(59, 130, 246, 0.8)');
            gradient.addColorStop(1, 'rgba(59, 130, 246, 0.1)');
            
            votingChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '票数',
                        data: data,
                        backgroundColor: gradient,
                        borderColor: '#3B82F6',
                        borderWidth: 2,
                        borderRadius: 6,
                        barPercentage: 0.6,
                        categoryPercentage: 0.7,
                        animation: {
                            duration: 1000,
                            easing: 'easeOutQuart'
                        }
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(30, 41, 59, 0.9)',
                            titleColor: '#F8FAFC',
                            bodyColor: '#CBD5E1',
                            borderColor: '#3B82F6',
                            borderWidth: 1,
                            padding: 12,
                            cornerRadius: 8,
                            displayColors: false,
                            callbacks: {
                                label: function(context) {
                                    return `票数: ${context.raw}票`;
                                }
                            }
                        },
                        // 显示柱状图上方的票数标签
                        datalabels: {
                            display: true,
                            color: '#1E293B',
                            font: {
                                weight: 'bold',
                                size: 12
                            },
                            formatter: function(value) {
                                return value + '票';
                            },
                            anchor: 'end',
                            align: 'top'
                        },
                        animation: {
                            animateScale: true,
                            animateRotate: true
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                font: {
                                    family: 'Inter',
                                    size: 12
                                },
                                color: '#64748B',
                                maxRotation: 45,
                                minRotation: 0
                            }
                        },
                        y: {
                            beginAtZero: true,
                            max: 100,
                            grid: {
                                color: 'rgba(226, 232, 240, 0.5)'
                            },
                            ticks: {
                                font: {
                                    family: 'Inter',
                                    size: 12
                                },
                                color: '#64748B',
                                callback: function(value) {
                                    return value + '票';
                                }
                            }
                        }
                    },
                    interaction: {
                        mode: 'index',
                        intersect: false
                    }
                }
            });
        }

        // 更新数据展示
        function updateDataDisplay(data) {
            // 排序数据
            const sortedData = Object.entries(data)
                .sort((a, b) => b[1] - a[1])
                .map(entry => ({ name: entry[0], score: entry[1] }));
            
            // 提取标签和数据
            const labels = sortedData.map(item => item.name);
            const scores = sortedData.map(item => item.score);
            
            // 更新图表
            initChart(labels, scores);
            
            // 更新统计信息
            if (sortedData.length > 0) {
                // 最高分选手
                const highestScorer = sortedData[0];
                document.getElementById('highest-score').textContent = 
                    `${highestScorer.name}: ${highestScorer.score}票`;
                
                // 平均分
                const averageScore = scores.reduce((sum, score) => sum + score, 0) / scores.length;
                document.getElementById('average-score').textContent = 
                    averageScore.toFixed(1) + '票';
                
                // 选手数量
                document.getElementById('contestant-count').textContent = sortedData.length + '人';
            }
            
            // 更新最后更新时间
            lastUpdateTime = new Date();
            const timeString = lastUpdateTime.toLocaleTimeString('zh-CN');
            document.getElementById('last-update').textContent = `最后更新: ${timeString}`;
        }

        // 获取指定轮次的数据
        function fetchRoundData(round) {
            currentRound = round;
            
            // 更新按钮样式
            document.querySelectorAll('.round-btn').forEach(btn => {
                if (btn.dataset.round === round) {
                    btn.classList.add('bg-primary', 'text-white');
                    btn.classList.remove('text-dark');
                } else {
                    btn.classList.remove('bg-primary', 'text-white');
                    btn.classList.add('text-dark');
                }
            });
            
            // 显示加载状态
            document.getElementById('highest-score').innerHTML = '<span class="animate-pulse">加载中...</span>';
            document.getElementById('average-score').innerHTML = '<span class="animate-pulse">加载中...</span>';
            document.getElementById('contestant-count').innerHTML = '<span class="animate-pulse">加载中...</span>';
            
            // 获取数据
            fetch(`/api/voting_data/${round}`)
                .then(response => response.json())
                .then(data => {
                    updateDataDisplay(data);
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    // 使用模拟数据
                    const mockData = {
                        '张三': 85,
                        '李四': 90,
                        '王五': 78,
                        '赵六': 92,
                        '钱七': 88,
                        '孙八': 80
                    };
                    updateDataDisplay(mockData);
                });
        }

        // 设置轮次按钮点击事件
        document.querySelectorAll('.round-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                fetchRoundData(this.dataset.round);
            });
        });

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            fetchRoundData('1');
            
            // 每6秒自动刷新数据
            setInterval(function() {
                fetchRoundData(currentRound);
            }, 6000);
        });
    </script>
</body>
</html>